package cn.liyunqi.findimg.controller;

import cn.liyunqi.findimg.task.BaiduTask;
import cn.liyunqi.findimg.task.ProgressBarViewTask;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;

import java.net.URL;
import java.text.DecimalFormat;
import java.util.List;
import java.util.ResourceBundle;

public class ProgressBarViewController extends BaseFXController{

    private FindImgMainController findImgMainController;

    private ProgressBarViewTask progressBarViewTask;

    @FXML
    private Label labMsg;

    @FXML
    private ProgressBar progressBar;

    @FXML
    private Label labPercent;

    @Override
    public void initialize(URL location, ResourceBundle resources) {

    }

    public void doTask(ProgressBarViewTask progressBarViewTask) {
        this.progressBarViewTask = progressBarViewTask;

        this.progressBarViewTask.setProgressBarViewController(this);

        Task baiduTask = progressBarViewTask;

        progressBar.progressProperty().unbind();
        progressBar.progressProperty().bind(baiduTask.progressProperty());

        baiduTask.messageProperty().addListener(new ChangeListener<String>() {
            public void changed(ObservableValue<? extends String> observable, String oldValue,
                                String newValue) {
                System.out.println(newValue);
            }
        });
        new Thread(baiduTask).start();

        //baiduTask.cancel();
    }

    public FindImgMainController getFindImgMainController() {
        return findImgMainController;
    }

    public void setFindImgMainController(FindImgMainController findImgMainController) {
        this.findImgMainController = findImgMainController;
    }


    public void updateProgress(String msg ,double currentSpeed,double totalSpeed){

        ProgressBarViewController that = this;

        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                that.labMsg.setText(msg);

                if(totalSpeed > 0){

                    DecimalFormat df = new DecimalFormat("#.00");
                    that.labPercent.setText(df.format(currentSpeed / totalSpeed * 100) + "%");
                }else{
                    that.labPercent.setText("--");
                }
            }
        });

    }

    public void updateMsg(String msg) {

        ProgressBarViewController that = this;

        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                that.labMsg.setText(msg);
            }
        });
    }

}
